package com.ctbu.score.service.impl;

import com.ctbu.score.domain.Rank;
import com.ctbu.score.domain.Score;
import com.ctbu.score.mapper.ScoreMapper;
import com.ctbu.score.mapper.StudentMapper;
import com.ctbu.score.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ScoreServiceImpl
 **/
@Service
public class ScoreServiceImpl  implements ScoreService {

    @Autowired
    private ScoreMapper scoreMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Score> getAllScores() {
        return scoreMapper.selectAllScores();
    }

    @Override
    public List<Score> selectByStuId(String stuId) {
        return scoreMapper.selectScoreByStuId(stuId);
    }

    @Override
    public List<Score> selectByStuIdAndScoTerm(String stuId, String scoTerm) {
        return scoreMapper.selectScoreByStuIdAndTerm(stuId,scoTerm);
    }

    @Override
    public int addScore(Score score) {
        return scoreMapper.insertScore(score);
    }

    @Override
    public int deleteScoreById(int scoId) {
        return scoreMapper.deleteScoreById(scoId);
    }

    @Override
    public Score selectScoreByStuIdAndSubName(String stuId, String subName) {
        return scoreMapper.selectScoreByStuIdAndSubName(stuId,subName);
    }

    @Override
    public Score selectScoreByScoId(int scoId) {
        return scoreMapper.selectScoreByScoId(scoId);
    }

    @Override
    public List<Rank> selectRankByTerm(String scoTerm) {
        List<Rank> ranks = scoreMapper.selectRankByTerm(scoTerm);
        for (Rank r :ranks) {
            Map<String, Integer> reamap=new HashMap<>();
            List<Map<String, Integer>> maps = scoreMapper.selectScoreMap(r.getStuId(), r.getScoTerm());
            for (Map map:maps)
            {
                reamap.put((String)map.get("sub_name"),(Integer) map.get("sco_num"));
            }
            r.setStuName(studentMapper.selectNameById(r.getStuId()));
            r.setScomap(reamap);
        }
        return ranks;
    }

    @Override
    public List<Rank> selectRankByTermAndStuClass(String scoTerm, String stuClass) {
        List<Rank> ranks=scoreMapper.selectRankByTermAndStuId(studentMapper.selectIdByClass(stuClass),scoTerm);
        for (Rank r :ranks) {
            Map<String, Integer> reamap=new HashMap<>();
            List<Map<String, Integer>> maps = scoreMapper.selectScoreMap(r.getStuId(), r.getScoTerm());
            for (Map map:maps)
            {
                reamap.put((String)map.get("sub_name"),(Integer) map.get("sco_num"));
            }
            r.setStuName(studentMapper.selectNameById(r.getStuId()));
            r.setScomap(reamap);
        }
        return ranks;
    }
}
